package cn.bigcontainer.alt.workflow.extension.impl;

import javax.annotation.Resource;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.common.util.WoVelocityKit;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.po.MViewProperty;
import cn.bigcontainer.alt.workflow.dto.MTaskDefinitionDto;
import cn.bigcontainer.alt.workflow.dto.MWorkflow;
import cn.bigcontainer.alt.workflow.extension.TaskRouter;
import cn.bigcontainer.alt.workflow.mapper.MTaskInstanceMapper;

@Component
@Primary
public class TaskRouterDefault implements TaskRouter {

    @Resource
    private WoVelocityKit velocityKit;

    @Resource
    private MTaskInstanceMapper taskInstanceMapper;

    @Override
    public String getNextTaskId(MTaskDefinitionDto currentTask) {
        MViewDto formView = currentTask.getFormView();
        MWorkflow workflow = (MWorkflow) formView.getApp();
        String instanceId = currentTask.getProcessInstanceId();
        if (!WoKit.isEmpty(currentTask.getTaskExpression())) {
            return currentTask.parseTaskExpression();
        }
        // 如果当前是审批节点，需要获取审批结果
        if (currentTask.getReview() == 1) {
            for (MViewProperty p : currentTask.getFormView().getProperties()) {
                if (p.getName().equals(p.getView().getName() + "结果")) {
                    String result = workflow.getObject().getRequest().getString(p.getId());
                    // 审批不通过并打回
                    if ("3".equals(result)) {
                        return workflow.getTasks().get(0).getId();
                    }
                    // 审批不通过并结束
                    if ("4".equals(result)) {
                        return "-1";
                    }
                }
            }
        }
        for (int i = 0; i < workflow.getTasks().size(); i ++) {
            if (currentTask == workflow.getTasks().get(i)) {
                if (i < workflow.getTasks().size() - 1) {
                    // 下一个任务id
                    return workflow.getTasks().get(i + 1).getId();
                }
                // 结束
                return "-1";
            }
        }
        return null;
    }
}
